/*
 * r480r.c
 *
 *  Created on: 2021年10月15日
 *      Author: wuwenfeng
 */


#include "r480r.h"
#define read_infrared  HAL_GPIO_ReadPin(infeaed_GPIO_Port,infeaed_Pin)

extern TIM_HandleTypeDef htim14;
uint16_t timer_100us_tick=0;
int read_bit_flag=0;
int read_char_flag=0;
char read_data_buffer[3];
char read_begin=0;

void r480_init()
{
	HAL_TIM_Base_Start_IT(&htim14);
	r480.times=0;
}

void read_433_exit()
{

	char a=read_infrared;
	int b;
	if(read_begin==0)
	{
		if(a==0)
		{
			timer_100us_tick=0;
			return ;
		}else
		{
			if(timer_100us_tick>70&&timer_100us_tick<100)
			{
				read_begin=1;
				r480.times++;
				read_bit_flag=0;
				read_char_flag=0;
				timer_100us_tick=0;
				return ;
			}
		}

	}else
	{
		if(timer_100us_tick<5)
		{
			timer_100us_tick=0;
			return ;
		}else if(timer_100us_tick<12)
		{
			read_data_buffer[read_char_flag]<<=1;
			if(a==1)
			{
				read_data_buffer[read_char_flag]|=0x01;
			}
			read_bit_flag++;
			if(read_bit_flag==8)
			{
				read_bit_flag=0;
				read_char_flag++;
				if(read_char_flag==3)
				{
					//got data

					read_char_flag=0;
					timer_100us_tick=0;

					r480.add[0]=read_data_buffer[0];
					r480.add[1]=read_data_buffer[1];
					r480.key=read_data_buffer[2];
				}
			}
			timer_100us_tick=0;
			return ;
		}else//time out
		{
			read_begin=0;
			timer_100us_tick=0;
			return ;
		}
	}

}

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
	switch(GPIO_Pin)
	{
		case infeaed_Pin:
			read_433_exit();
			return ;
			break;
	}
}
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)//100us
{
    if (htim == (&htim14))
        {
    	timer_100us_tick++;
        }
}
